package fr.pentalog.ctc.controller.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import ro.peoplecentric.ctc.common.entity.Item;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.service.ItemService;
import fr.pentalog.ctc.model.IdList;
import fr.pentalog.ctc.util.WebAppConstants;

/**
 * @author Danut Chindris
 * @since September 23, 2013
 */

@Controller
public class DeleteController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private ItemService itemService;

	@RequestMapping(value = "/delete")
	public String deleteItems(@ModelAttribute IdList ids, @RequestParam(value = "id", required = false) Long id) throws ApplicationException {
		List<Long> itemIds = new ArrayList<Long>();
		if (id != null) {
			itemIds.add(id);
		}
		else if (ids != null && ids.getIds() != null && !ids.getIds().isEmpty()) {
			String[] idsArray = ids.getIds().split(WebAppConstants.UNDERSCORE);
			for (String idString : idsArray) {
				try {
					itemIds.add(Long.parseLong(idString));
				}
				catch (NumberFormatException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		for (Long itemId : itemIds) {
			Item item = itemService.getById(itemId);
			itemService.deleteItem(item);
		}
		return WebAppConstants.ITEMS_REDIRECT_VIEW_NAME;
	}
}
